package cn.dev123.util.tools;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class DES
{
	private static byte[]   iv  = { '1', '2', '3', '4', '5', '6', '7', '8' };
	private static String	keyStr = "12345678";

	public static String encryptDES(String encryptString) throws Exception
	{
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		
		SecretKeySpec key = new SecretKeySpec(keyStr.getBytes(), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
		byte[] encryptedData = cipher.doFinal(encryptString.getBytes());

		return Base2.encode(encryptedData);
	}
	
	public static String decryptDES(String decryptString) throws Exception
	{
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		
		SecretKeySpec key = new SecretKeySpec(keyStr.getBytes(), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
		byte decryptedData[] = cipher.doFinal(toByte(decryptString));

		return new String(decryptedData);
	}
	
	public static byte[] toByte(String hexString)
	{
		int len = hexString.length() / 2;
		byte[] result = new byte[len];
		for (int i = 0; i < len; i++)
			result[i] = Integer.valueOf(
					hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
		return result;
	}
	
	public static String toHex(byte[] buf)
	{
		if (buf == null)
			return "";
		StringBuffer result = new StringBuffer(2 * buf.length);
		for (int i = 0; i < buf.length; i++)
			appendHex(result, buf[i]);

		return result.toString();
	}
	
	private final static String	HEX	= "0123456789ABCDEF";

	private static void appendHex(StringBuffer sb, byte b)
	{
		sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
	}
}
